import axios from "axios";
import store from "@/store";
import { Notification } from "element-ui";

// 创建axios实例
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
});

// 配置请求前拦截器
instance.interceptors.request.use(
  (config) => {
    const hasToken = store.state.token.tokenInfo;
    if (hasToken) {
      let token = JSON.parse(hasToken);
      config.headers = { [token.tokenName]: token.tokenValue };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 配置响应后拦截器
instance.interceptors.response.use(
  (response) => {
    // 100000:操作成功
    if (response.data.code === 100000) {
      return response.data;
    } else {
      Notification({
        title: "请求失败",
        message: response.data.message,
        type: "error",
        position: "bottom-left",
        duration: 3000,
      });
      return Promise.reject(new Error(response.data.message));
    }
  },
  (error) => {
    Notification({
      title: "请求失败",
      message: error.message,
      type: "error",
      position: "bottom-left",
      duration: 3000,
    });
    return Promise.reject(error);
  }
);

export default instance;
